import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { BaseHttpService } from '../../services/baseHttp.service';
import { StorageService } from '../../services/storage.service';

/* 
Portfolio page
    -portfolio search
Main menu
    -company search    
*/
export enum SearchType {
    company = 0,
    portfolio = 1
}

/**
 * Search main service
 * 
 * Authos: Sorin Spiru
 * Date: 13.01.2018
 */
@Injectable()
export class SearchService extends BaseHttpService {
    constructor(private http: HttpClient) {
        super();
    }

    /**
     * Search for a company or protfolio
     * @param type Type of search to be made: company or portfolio
     * @param term The name to search for
     * @param skip Index to skip to
     * @param take Number of records to take that satisfy the condition
     */
    public search(type: SearchType, term: string, skip: number, take: number): Observable<any[]> {
        let params = new HttpParams();
        let userInfo = StorageService.get().userInfo;
        params = params.set("userId", userInfo.userId)
        .set("accountId", userInfo.accountId);
        
        let url;
        switch(type){
            case SearchType.company: {   
                //because of the HppClient issue with '+' and probably other special chars, we set the name parameter into the url
                url = 'companyserv/api/v1/companies?term=' + encodeURIComponent(term);
                params = params.set("skip", skip.toString())
                .set("take", take.toString());
                break;
            }
            case SearchType.portfolio: {
                //because of the HppClient issue with '+' and probably other special chars, we set the name parameter into the url
                url = 'portfolioserv/api/v1/portfolios?namePortfolio=' + encodeURIComponent(term);
                let listOptions: any = {
                    skip: skip,
                    take: take,
                    orderBy: ['Name'],
                    orderAscending: true,
                    includeAllFields: false,
                    getCount: false
                };
                params = params.set("isMyPortfolio", 'true')                
                .set("sharingStatus", '0')
                .set("portfolioType", '1')
                .set("isNameEqual", 'false');
                params = this.urlEncodeObject(listOptions, params);                    
                break;
            }
        }

        return this.http.get<any[]>(this.serverUrl + url, {params: params});
    }
}